package com.itbaizhan.shopping_admin_service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itbaizhan.shopping_admin_service.mapper.AdminMapper;
import com.itbaizhan.shopping_common.pojo.Admin;
import com.itbaizhan.shopping_common.pojo.Permission;
import com.itbaizhan.shopping_common.service.AdminService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@DubboService
@Transactional
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;


    @Override
    public Admin findByUsername(String username) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        Admin admin = adminMapper.selectOne(queryWrapper);
        return admin;
    }

    @Override
    public List<Permission> findPermissionByUsername(String username) {
        return adminMapper.findPermissionByUsername(username);
    }

    @Override
    public void add(Admin admin) {
        adminMapper.insert(admin);
    }

    @Override
    public void update(Admin admin) {
        String password = admin.getPassword();
        if(!StringUtils.hasText(password)) {
            Admin admin1 = adminMapper.findById(admin.getAid());
            admin.setPassword(admin1.getPassword());
        }
        adminMapper.updateById(admin);
    }

    @Override
    public void delete(Long aid) {
        // 删除该管理员所拥有的全部角色
        adminMapper.deleteAllRoleToAdmin(aid);

        adminMapper.deleteById(aid);
    }

    @Override
    public Admin findById(Long id) {
        return adminMapper.findById(id);
    }

    @Override
    public Page<Admin> search(int page, int size) {
        return adminMapper.selectPage(new Page<>(page, size), null);
    }

    @Override
    public void updateRoleToAdmin(Long aid, Long[] rids) {
        // 删除该管理员所拥有的全部角色
        adminMapper.deleteAllRoleToAdmin(aid);
        // 为该管理员添加角色
        for (Long rid : rids) {
            adminMapper.addRoleToAdmin(aid, rid);
        }
    }
}
